<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @open="handleDialogOpen"
    @close="handleCloseDialog"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <!-- 遍历角色列表 -->
      <el-checkbox
        v-for="role in roleList"
        :key="role.id"
        :label="role.id"
      >{{ role.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button
        type="primary"
        size="small"
        @click="assignRole"
      >确定</el-button>
      <el-button
        size="small"
        @click="handleCloseDialog"
      >取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      checkList: [],
      roleList: [],
      loading: false
    }
  },
  methods: {
    async assignRole() {
      await this.apis.employees.assignRole(this.userId, this.checkList)
      this.$message.success('分配权限成功')
      this.handleCloseDialog()
    },
    async handleDialogOpen() {
      this.loading = true
      await Promise.all([this.getRoleList(), this.getCheckList()])
      this.loading = false
    },
    handleCloseDialog() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
      this.roleList = []
    },
    async getRoleList() {
      const { rows } = await this.apis.setting.getRoleList({ page: 1, pagesize: 999 })
      this.roleList = rows
    },
    async getCheckList() {
      const { roleIds } = await this.apis.user.getUserDetailById(this.userId)
      this.checkList = roleIds
    }
  }
}
</script>
